/**
 * @Copyright:Copyright (c) 1992 - 2015
 * @Company: TengTong
 */
package com.tengtong.duang.commons.convert.support;

import java.util.Collection;
import java.util.List;
import java.util.Set;

import com.tengtong.duang.commons.collections.ListUtils;
import com.tengtong.duang.commons.collections.SetUtils;
import com.tengtong.duang.commons.convert.ConditionalConverter;
import com.tengtong.duang.commons.utils.ReflectUtils;

/**
 * 字符串转成一个 list , set 之类的容器类
 * 
 * @author mling
 *
 */
public class StringToCollectionConverter implements ConditionalConverter{
	
	/* (non-Javadoc)
	 * @see com.tengtong.duang.commons.convert.ConditionalConverter#convert(java.lang.Object, java.lang.Class)
	 */
	@Override
	public Object convert(Object source, Class<?> targetType){
		if(source == null){
			return null;
		}
		
		try{
			Collection<String> result = null;
			if(ReflectUtils.canNewInstance(targetType)){
				result = (Collection<String>) targetType.newInstance();
			}else if(ReflectUtils.isInheritance(targetType, List.class)){
				result = ListUtils.newSimpleList();
			}else if(ReflectUtils.isInheritance(targetType, Set.class)){
				result = SetUtils.newSimpleSet();
			}
			
			if(result != null){
				result.add(source.toString());
			}
			
			return result;
		}catch(Exception e){
			ReflectUtils.toRuntimeException(e);
		}
		
		return null;
	}

	/* (non-Javadoc)
	 * @see com.tengtong.duang.commons.convert.ConditionalConverter#matches(java.lang.Class, java.lang.Class)
	 */
	@Override
	public boolean matches(Class<?> sourceType, Class<?> targetType) {
		return ReflectUtils.isInheritance(targetType, Collection.class) && String.class.equals(sourceType);
	}

}
